package com.zxycloud.interceptor;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

//API接口拦截器
public class ApiAuthInterceptor extends HandlerInterceptorAdapter {

	

	/*@Value("${api.debug}")
	private Boolean apiDebug;*/

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		/*String token = RequestAnalysisService
				.getApiTokenByRequestHeader(request);
		String ip = RequestAnalysisService.getRemoteHost(request);
//		String ip = "192.168.32.2";
		if (apiDebug) {
			// debug模式
			System.out
					.println("Debug environment!-----------------------------------------");
			request.setAttribute("projectId",
					"cd30e238c31f4a2baeff3b4c27c4d409");
			return true;
		} else {
			// 正式模式
			if (token == null || token.isEmpty()) {
				// token不存在
				ApiJsonResultModel result = new ApiJsonResultModel();
				result.setCode("P01000");
				result.setMessage("apiToken缺失");
				response.setCharacterEncoding("UTF-8");
				response.setStatus(400);
				response.setContentType("application/json; charset=utf-8");
				PrintWriter out = null;
				try {
					out = response.getWriter();
					out.append(JSON.toJSONString(result));
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					if (out != null) {
						out.close();
					}
				}
				return false;
			} else {
				String projectId = apiPermissionService
						.getProjectIdFromSSOByToken(token, ip);
				if (projectId.length() == 6) {
					ApiJsonResultModel result = new ApiJsonResultModel();
					result.setCode(projectId);
					if (projectId == "P00000") {
						result.setMessage("服务器错误");
						response.setStatus(500);
					} else {
						result.setMessage("认证失效");
						response.setStatus(401);
					}
					response.setCharacterEncoding("UTF-8");
					response.setContentType("application/json; charset=utf-8");
					PrintWriter out = null;
					try {
						out = response.getWriter();
						out.append(JSON.toJSONString(result));
					} catch (IOException e) {
						e.printStackTrace();
					} finally {
						if (out != null) {
							out.close();
						}
					}
					return false;
				} else {
					request.setAttribute("projectId", projectId);
					return true;
				}
			}
		}*/
		return true;	
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}

}
